package com.jsh.erp;

import com.jsh.erp.utils.ComputerInfo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.lang.management.ManagementFactory;
import java.util.Arrays;

@SpringBootApplication
@MapperScan("com.jsh.erp.datasource.mappers")
@ServletComponentScan
@EnableScheduling
public class ErpApplication {

    public static void main(String[] args) {
        System.out.println("=== 应用启动诊断信息 ===");
        System.out.println("JVM 启动参数: " + ManagementFactory.getRuntimeMXBean().getInputArguments());
        System.out.println("Main 方法参数: " + Arrays.toString(args));

        try {
            ConfigurableApplicationContext context = SpringApplication.run(ErpApplication.class, args);

            // 检查应用状态
            checkApplicationState(context);

            Environment environment = context.getBean(Environment.class);
            System.out.println("启动成功，后端服务API地址：http://" + ComputerInfo.getIpAddr() + ":"
                    + environment.getProperty("server.port") + "/jshERP-boot/doc.html");
            System.out.println("您还需启动前端服务，启动命令：yarn run serve 或 npm run serve，测试用户：jsh，密码：123456");

            System.out.println("应用已启动并保持运行...");

            // Spring Boot 会自动保持应用运行，不需要额外的阻塞代码

        } catch (Throwable t) {
            System.err.println("应用启动失败: " + t.getMessage());
            t.printStackTrace();
            System.exit(1); // 启动失败时明确退出
        }
    }

    private static void checkApplicationState(ConfigurableApplicationContext context) {
        System.out.println("=== 应用状态检查 ===");

        // 检查 Web 相关 Bean
        try {
            String[] dispatcherBeans = context.getBeanNamesForType(org.springframework.web.servlet.DispatcherServlet.class);
            System.out.println("DispatcherServlet Beans: " + Arrays.toString(dispatcherBeans));

            // 检查端口
            String port = context.getEnvironment().getProperty("server.port");
            System.out.println("服务器端口: " + port);

        } catch (Exception e) {
            System.err.println("状态检查失败: " + e.getMessage());
        }

        System.out.println("活跃的Bean数量: " + context.getBeanDefinitionCount());
        System.out.println("应用上下文: " + context.getClass().getName());
    }
}